package com.springboot.frame.starter.web.intf;

import java.io.IOException;
import java.lang.reflect.Type;

import com.springboot.fram.core.digest.Encrypt;
import com.springboot.frame.web.annotation.SecurityParameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;


/**
 * @author monkey
 * @desc 请求数据解密
 * @date 2018/10/25 20:17
 * RequestBodyAdviceAdapter 为 RequestBodyAdvice子类
 */
@Slf4j(topic = "request-intf-decode")
@ControllerAdvice
public class DecodeRequestBodyAdvice extends RequestBodyAdviceAdapter {

    @Autowired
    private IntfEncryptionProperties intfEncryptionProperties;

    @Override
    public boolean supports(MethodParameter methodParameter, Type type,
                            Class<? extends HttpMessageConverter<?>> aClass) {
        SecurityParameter securityParameter = methodParameter.getMethodAnnotation(SecurityParameter.class);
        return (methodParameter.hasMethodAnnotation(SecurityParameter.class) || methodParameter.hasParameterAnnotation(SecurityParameter.class)) && securityParameter.inDecode();
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter, Type type,
                                           Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        try {
            log.info("对方法method :【" + methodParameter.getMethod().getName() + "】请求数据进行解密");
            return new RequstHttpInputMessage(inputMessage, intfEncryptionProperties);
        } catch (Exception e) {
            log.error("对方法method :【" + methodParameter.getMethod().getName() + "】请求数据进行解密出现异常：" + e.getMessage());
        }
        return super.beforeBodyRead(inputMessage, methodParameter, type, aClass);
    }

}
